<template>
  <div class=" zy-content ">
    <back-level @click="close"/>
    <Card v-if="$route.query.status !=='detail'" :title="`${$t('spareParts.FromScrap')}`" class="detail-content0layout">
      <template>
        <div class="basic-info">
          <!--            <div class="basic-info-title">-->
          <!--              <h2>{{ $t('spareParts.FromScrap') }}</h2>-->
          <!--            </div>-->
          <div class="basic-info-body">
            <Form label-position="right" class="search-form">
              <Row :gutter="16">
                <Col span="6">
                  <FormItem :label="$t('spareParts.PartNoGoodsNameSpecification')"> <!--料号/品名/规格  -->
                    <Select filterable
                            v-model="searchParams.materielNo"
                            :remote-method="remoteMethod"
                            @on-change="handleMaterielNo"
                            clearable
                            :placeholder="`${$t('common.inputInfo')}`">
                      <Option v-for="item of materielNoList"
                              :value="item.id"
                              :label="item.materielNo"
                              :key="item.id">
                        {{ item.materielNo + '-' + item.goodsName + '-' + item.specification }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem :label="$t('common.SpareNumber')"><!--备件编号  -->
                    <Select filterable
                            v-model="searchParams.backupNo"
                            :remote-method="remoteMethodBack"
                            @on-change="handleBackupNo"
                            clearable
                            :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="item of backupNoList"
                              :value="item.id"
                              :label="item.backupNo"
                              :key="item.id"/>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem :label="$t('spareParts.company')"><!--公司名称  -->
                    <Select v-model="searchParams.companyName"
                            @on-change="companySelectChange"
                            @on-clear="companyClear"
                            clearable :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="(item,index) of companyList"
                              :value="item.id"
                              :key="index">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem :label="$t('common.Warehouse')"><!--仓库名称  -->
                    <Select v-model="searchParams.backupId"
                            @on-change="warehouseSelectChange"
                            @on-clear="warehouseClear"
                            ref="warehouseSelect"
                            clearable :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="(item,index) of warehouseList"
                              :value="item.id"
                              :key="index">
                        {{ item.backupName }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem :label="$t('common.Rack')"><!--货架名称  -->
                    <Select v-model="searchParams.shelfId"
                            @on-change="shelvesSelectChange"
                            @on-clear="shelvesClear"
                            ref="shelvesSelect"
                            clearable :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="(item,index) of shelvesList" :value="item.id" :key="index">
                        {{ item.shelf }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">

                  <FormItem :label="$t('common.Location')">  <!--库位名称  -->
                    <Select v-model="searchParams.locationId"
                            ref="locationSelect"
                            clearable :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="(item,index) of locationList" :value="item.id" :key="index">
                        {{ item.location }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem :label="$t('spareParts.AssetType')"><!--资产类型  -->
                    <!--                                    <Input v-model="searchParams.assetTypeName"/>-->
                    <Select v-model="searchParams.assetTypeName"
                            clearable
                            @on-change="assetChange"
                            :placeholder="`${$t('common.selectInfo')}`">
                      <Option v-for="(item) of assetType"
                              :label="item.label"
                              :key="item.value"
                              :value="item.value"/>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6" align="center">
                  <div style="height:72px;display:flex;align-items:flex-end">
                    <p class="label hide-label">--</p>
                    <div class="ipt">
                      <Button class="search-btn" type="primary" v-if="$route.query.status !=='detail'"
                              @click="addInfolist">
                        {{ $t('保存添加') }}
                      </Button>
                    </div>
                  </div>
                </Col>
              </Row>
              <Row>
              </Row>
            </Form>
          </div>
        </div>
      </template>
    </Card>
    <Card :title="`${$t('spareParts.ToScrap')}`" class="detail-content0layout mt16">
      <div class="basic-info tableContent" style="border: none">
        <div class="basic-info-body">
          <Table :columns="tableColumns" :data="tablelist">
            <template slot-scope="{ row }" slot="companyName">
              <template v-if="$route.query.status ==='detail'">
                <span>{{ row.companyName }}</span>
              </template>
              <Select
                v-else
                :transfer="true"
                v-model="row.companyId"
                @on-change="companySelectChange(1,row)"
                disabled>
                <Option v-for="item of row.companyrowList"
                        :value="item.id"
                        :key="item.id" :label="item.name">
                </Option>
              </Select>
            </template>
            <template slot-scope="{ row }" slot="backupName">
              <template v-if="$route.query.status ==='detail'">
                <span>{{ row.warehouseName }}</span>
              </template>
              <Select
                v-else
                :transfer="true"
                v-model="row.backupId"
                @on-change="warehouseSelectChange(1,row)"
                disabled
                ref="warehouseSelect"
                :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of row.warehouserowList"
                        :value="item.id"
                        :key="item.id">
                  {{ item.backupName }}
                </Option>
              </Select>
            </template>
            <template slot-scope="{ row }" slot="shelfName">
              <template v-if="$route.query.status ==='detail'">
                <span>{{ row.shelfConfigName }}</span>
              </template>
              <Select
                v-else
                :transfer="true"
                v-model="row.shelfId"
                :disabled="$route.query.status ==='detail'"
                @on-change="shelvesSelectChange(1,row)"
                :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of row.shelvesrowList"
                        :value="item.id"
                        :key="item.id">
                  {{ item.shelf }}
                </Option>
              </Select>
            </template>
            <template slot-scope="{ row }" slot="location">
              <template v-if="$route.query.status ==='detail'">
                <span>{{ row.locationConfigName }}</span>
              </template>
              <Select
                v-else
                :transfer="true"
                v-model="row.locationId"
                @on-change="locationSelectChange(row)"
                :disabled="$route.query.status ==='detail'"
                :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item of row.locationrowList"
                        :value="item.id"
                        :key="item.id">
                  {{ item.location }}
                </Option>
              </Select>
            </template>
            <template slot-scope="{ row }" slot="scrapCount">
                            <span
                              v-if="$route.query.status ==='detail' || row.assetId !== 2">{{ row.scrapCount }}</span>
              <Input v-else
                     :disabled="$route.query.status ==='detail'"
                     v-model="row.scrapCount"
                     number
                     @on-keyup="levelCheck"
                     @on-change="outNumchange(row)"/>
            </template>

            <template slot-scope="{ row }" slot="assetsOriginal">
              <span v-if="$route.query.status ==='detail'">{{ row.assetsOriginal }}</span>
              <Input v-else
                     :disabled="$route.query.status ==='detail'|| row.assetId == 2"
                     @on-change="originalChange(row)"
                     v-model="row.assetsOriginal"
              />
            </template>
            <template slot-scope="{ row }" slot="assets">
              <span v-if="$route.query.status ==='detail'">{{ row.assets }}</span>
              <Input v-else
                     disabled
                     v-model="row.assets"
              />
            </template>
            <template slot-scope="{ row }" slot="useTime">
              <span v-if="$route.query.status ==='detail'">{{ row.useTime }}</span>
              <Input v-else-if="row.useTime ||'0'"
                     :disabled="$route.query.status ==='detail' || row.assetId == 2"
                     v-model="row.useTime"
              />
              <Date-picker
                :transfer="true"
                v-else type="daterange"
                placement="bottom-end"
                placeholder="选择日期"
                :disabled="$route.query.status ==='detail' || row.assetId == 2"
                @on-change="dateChang($event,row)"
              />
            </template>
            <template slot-scope="{ row }" slot="useDept">
              <span v-if="$route.query.status ==='detail'">{{ row.useDept }}</span>
              <Input v-else :disabled="$route.query.status ==='detail'"
                     @on-change="remarkNumchange(row)"
                     v-model="row.useDept"
              />
            </template>
            <template slot-scope="{ row }" slot="deptCostCenter">
              <span v-if="$route.query.status ==='detail'">{{ row.deptCostCenter }}</span>
              <Input v-else :disabled="$route.query.status ==='detail'"
                     @on-change="remarkNumchange(row)"
                     v-model="row.deptCostCenter"
              />
            </template>
            <template slot-scope="{ row }" slot="scrapReason">
              <span v-if="$route.query.status ==='detail'">{{ row.scrapReason }}</span>
              <Input v-else :disabled="$route.query.status ==='detail'"
                     v-model="row.scrapReason"
                     @on-change="remarkNumchange(row)"/>
            </template>

            <template v-if="$route.query.status !=='detail'" slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="delRow(row)">{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
      </div>
    </Card>
    <Card :title="`${$t('common.attachmentData')}`"
          class="detail-content0layout mt16">
      <div class="basic-info tableContent" style="border: none">
        <div class="basic-info-title  basic-info-title_bot" v-if="$route.query.status !=='detail'">
          <!--            <h2>{{ // $t('common.attachmentData') }}</h2>&lt;!&ndash;附件资料  &ndash;&gt;-->
          <template>
            <Upload :show-upload-list="false"
                    action=""
                    :before-upload="handleBeforeUpload"
            >
                            <span
                              style="height: 30px;width: 30px; display: inline-block; cursor: pointer;margin-left: 5px;">
                                <Icon type="ios-cloud-upload-outline"
                                      color="#187BDB"
                                      style="width: 100%;height: 100%; font-size: 30px;"/>
                            </span>
            </Upload>
          </template>
        </div>
        <div class="basic-info-body">
          <Row>
            <Tag color="blue"
                 type="border"
                 v-for="item in uploadList"
                 :key="item.fileName"
                 :closable="$route.query.status === 'edit'"
                 @click.native="handlePreView(item)"
                 @on-close="fileDelete(item)">
              {{ item.fileName }}
            </Tag>
          </Row>
        </div>
      </div>
    </Card>
    <Card v-if="$route.query.status ==='detail'" :title="`${$t('common.ApprovalInformation')}`"
          class="detail-content0layout mt16">
      <template>
        <div class="basic-info tableContent" style="border: none">
          <!--            <div class="basic-info-title  basic-info-title_bot">-->
          <!--              <h2>{{ $t('common.ApprovalInformation') }}</h2>-->
          <!--            </div>-->
          <div class="basic-info-body">
            <Table :columns="approvalColumns" :data="approvalTablelist"/>
          </div>
        </div>
      </template>
    </Card>
    <bottom-handle-wrap v-if="$route.query.status !=='detail'">
      <Button @click.prevent="close">
        {{ $t('common.Cancle') }}
      </Button>

      <Button type="primary" v-if="$route.query.status === 'edit'"
              @click.prevent="handleSumit('save')">
        {{ $t('common.submit') }}
      </Button>

      <Button type="primary" v-if="$route.query.status !=='edit'"
              @click.prevent="handleSumit('submit')">
        {{ $t('common.submit') }}
      </Button>
    </bottom-handle-wrap>
  </div>
</template>

<script>
import {
  getCompanyList,
  getBackupsByCompany,
  getShelfByBackupId,
  baogetLocationByShelfId
} from "@/api/index.js";

export default {
  name: "addScrapApply",
  data() {
    return {
      approvalColumns: [
        {
          title: `${this.$t('审批节点')}`,
          key: 'processNodeName',
          align: 'center'
        },
        {
          title: `${this.$t('common.Approvedby')}`,
          key: 'approvalByStr',
          align: 'center'
        },
        {
          title: `${this.$t('equipmentscrapped.Result')}`,
          key: 'approvalResult',
          align: 'center'
        },

        {
          title: `${this.$t('common.ApprovalTime')}`,
          key: 'approvalTime',
          align: 'center'
        },
        {
          title: `${this.$t('equipmentscrapped.Comments')}`,
          key: 'scrapApprovalMessage',
          align: 'center'
        },
      ],
      assetType: [
        {
          label: '非资产类',
          value: 2
        }],
      materielNoList: [],
      backupNoList: [],
      timerId: null,
      timeID: null,
      pageNum: 1,
      pageSize: 10,
      searchParams: {},
      orgList: [],
      companyList: [{id: '', name: '全部'}],
      warehouseList: [],
      shelvesList: [],
      locationList: [],
      idNum: 0,
      depreciationInfo: '',
      companyrowList: [],
      warehouserowList: [],
      shelvesrowList: [],
      locationrowList: [],
      tablelist: [],
      OAList: [],
      uploadList: [],
      approvalTablelist: [],
      materielNoObj: {},
      paramsInfo: {},
      backupNoObj: {},
      tableColumns: [
        {
          //title: `${this.$t('spareParts.PartNo')}`,
          title: `${this.$t('spareParts.PartNo')}`,
          key: 'materielNo',
          align: "center",
        },
        {
          // title: `${this.$t('common.SpareNumber')}`,
          title: `${this.$t('common.SpareNumber')}`,
          key: 'backupNo',
          align: "center",
        },
        {
          //title: '品名',
          title: `${this.$t('common.GoodsName')}`,
          key: 'goodsName',
          align: "center",
        },
        {
          //title: '规格',
          title: `${this.$t('spareParts.Specification')}`,
          key: 'specification',
          align: "center",
        },
        {
          //title: `${this.$t('spareParts.company')}`,
          title: `${this.$t('spareParts.company')}`,
          key: 'companyName',
          slot: "companyName",
          align: "center",
        },
        {
          //title: '仓库名称',
          title: `${this.$t('common.Warehouse')}`,
          key: 'backupName',
          slot: "backupName",
          align: "center",
        },
        {
          //title: '货架',
          title: `${this.$t('spareParts.Rack')}`,
          key: 'shelfName',
          slot: "shelfName",
          align: "center",
        },
        {
          //title: `${this.$t('spareParts.Location')}`,
          title: `${this.$t('spareParts.Location')}`,
          key: 'location',
          slot: "location",
          align: "center",
        },
        {
          // title: '报废数量',
          title: `${this.$t('spareParts.ScrapQuantity')}`,
          key: 'scrapCount',
          slot: "scrapCount",
          align: "center",
        },
        {
          title: `${this.$t('equipmentscrapped.OriginalValue')}`,
          key: 'assetsOriginal',
          slot: "assetsOriginal",
          minWidth: 250,
          align: "center",
        },
        {
          title: `${this.$t('equipmentscrapped.ResidualValue')}`,
          key: 'assets',
          slot: "assets",
          align: "center",
        },
        {
          title: `${this.$t('使用年限')}`,
          key: 'useTime',
          slot: "useTime",
          align: "center",
        },
        // {
        //   title: `折旧年限`,
        //   key: 'depreciation',
        //   slot: "depreciation",
        //   align: "center",
        // },
        {
          title: `${this.$t('equipmentscrapped.UsedDept')}`,
          key: 'useDept',
          slot: "useDept",
          align: "center",
        },
        {
          title: `${this.$t('equipmentscrapped.CostCenter')}`,
          key: 'deptCostCenter',
          slot: "deptCostCenter",
          align: "center",
        },
        {
          //title: '报废原因',
          title: `${this.$t('spareParts.ScrapReason')}`,
          key: 'scrapReason',
          slot: "scrapReason",
          align: "center",
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          fixed: 'right',
          minWidth: 200,
          align: "center"
        }
      ],
    }
  },
  created() {
    this.tableColumns.forEach((m) => (m.minWidth ? "" : (m.minWidth = 150)));
    this.getCompanyList()
    this.$nextTick(() => {
      if (this.$route.query.status === 'edit' || this.$route.query.status === 'detail') {
        this.getDatainfo()
      }
    })
    this.getAsstetype()
    // this.searchList()
  },
  methods: {
    getTable(_arr) {
      this.tablelist = []
      const arr = _arr.map(obj => ({
        id: obj.id,
        backupPurchaseId: obj.backupPurchaseId,
        materielNo: obj.materielNo, //料号
        backupNo: obj.backupNo,//备件编号
        locationId: obj.locationConfigId,//库位id
        assets: obj.assets,//资产残值
        manageType: obj.manageType,//管理类型
        assetId: obj.assetId,//资产分类主键id
        assetsOriginal: obj.assetsOriginal,//资产原值
        scrapCount: obj.scrapCount,//报废数量
        useTime: obj.useTime,//使用时间
        useDept: obj.useDept,//使用部门
        deptCostCenter: obj.deptCostCenter,//部门成本中心
        scrapReason: obj.scrapReason,//报废原因
        goodsName: obj.goodsName,
        specification: obj.specification,
        companyName: obj.companyName,
        warehouseName: obj.warehouseName,
        shelfConfigName: obj.shelfConfigName,
        locationConfigName: obj.locationConfigName,
        companyId: obj.companyId,
        backupId: obj.backupConfigId,
        shelfId: obj.shelfConfigId
      }))
      if (arr && arr.length) {
        arr.forEach(async tableObj => {
          await this.getCompanyList(tableObj)
          await this.getBackupsByCompany(1, tableObj)
          await this.getShelfByBackupId(1, tableObj);
          await this.baogetLocationByShelfId(1, tableObj, {scrapStatus: 1});
          this.tablelist.push(tableObj)
        })
      }
    },
    getDatainfo() {
      this.axios({
        method: 'get',
        url: '/dms/backup/scrapApply/info',
        params: {
          id: this.$route.query.id,
          approvalFlowSort: this.$route.query.approvalFlowSort
        }
      }).then(res => {
        if (res.data && res.data.backupScrapApplyVos.length) {
          if (res.data.backupScrapApplyVos && res.data.backupScrapApplyVos.length) {
            this.getTable(res.data.backupScrapApplyVos)
          }
          if (res.data.attachmentVOS && res.data.attachmentVOS.length) {
            this.uploadList = res.data.attachmentVOS
          }
          if (res.data.approvalVos && res.data.approvalVos.length) {
            this.approvalTablelist = res.data.approvalVos
          }
        }
      })
    },
    handlePreView(item) {
      if (item) {
        window.open(this.util.filePathToUrl(item.filePath));
      }
    },
    fileDelete(item) {
      this.uploadList = this.uploadList.filter(val => val.filePath !== item.filePath)
    },
    //文件上传
    handleBeforeUpload(file) {
      let formData = new FormData();
      formData.append("dir", 'device')
      formData.append("file", file)
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config,
      }).then(res => {
        if (res.code === 200) {
          this.uploadList.push({
            createBy: localStorage.getItem('ziyunFactoryUserId'),
            fileName: res.data.fileName,
            fileUrl: res.data.fileUrl,
            filePath: res.data.filepath,
            suffix: res.data.suffix,
          })
        }
      })
      return false
    },
    //计算资产残值
    getassetsData(row) {
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      const params = {
        days: row.useTime,
        original: row.assetsOriginal,
        depreciation: this.depreciationInfo
      }
      this.timerId = setTimeout(() => {
        this.axios({
          method: 'get',
          url: '/dms/backup/scrapApply/calculationAsset',
          params
        }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.$set(row, 'assets', res.data)
              this.tablelist.forEach(val => {
                if (val.id === row.id) {
                  val.assets = res.data
                }
              })
            }
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        })
      }, 600)
    },
    getDays(start, end) {
      let dateSpan, iDays
      start = Date.parse(start)
      end = Date.parse(end)
      dateSpan = end - start
      dateSpan = Math.abs(dateSpan)
      iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
      return iDays;
    },
    originalChange(row) {
      this.tablelist.forEach(val => {
        if (val.id === row.id) {
          val.assetsOriginal = row.assetsOriginal
          val.useTime = row.useTime
        }
      })
      if (row.useTime && row.assetsOriginal && this.depreciationInfo) {
        this.getassetsData(row)
      }
    },
    dateChang(val, row) {
      if (val && val.length) {
        const days = this.getDays(val[0], val[1])
        this.$set(row, 'useTime', days)
        if (row.assetsOriginal) {
          this.originalChange(row)
        }
      }
    },
    assetChange(val) {
      if (val) {
        this.clearBackup()
      }
    },
    //查询资产分类
    getAsstetype() {
      let params = {
        // pageNum:1,
        // pageSize:100,
        belong: 2
      };
      this.axios({
        method: 'get',
        url: '/dms/assetCategory/getListByName',
        params

      }).then(res => {
        if (res.code === 200) {
          const arr = res.data.map(val => ({
            label: val.details,
            value: val.id
          }))
          this.assetType = this.assetType.concat(arr)
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    levelCheck(e) {
      e.target.value = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
      const reg = /[^\d.]/g;
      e.target.value = e.target.value.replace(reg, "");
      e.target.value = e.target.value.replace(/^\./g, "");
      e.target.value = e.target.value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      e.target.value = e.target.value.replace(
        /^(\-)*(\d+)\.(\d\d).*$/,
        "$1$2.$3"
      );
    },
    locationSelectChange(row) {
      this.clearBackup()
      this.tablelist.forEach(val => {
        if (val.id === row.id) {
          val.locationId = row.locationId
        }
      })
    },
    outNumchange(row) {
      if (this.timeID) {
        clearTimeout(this.timeID)
      }
      this.timeID = setTimeout(() => {
        this.tablelist.forEach(val => {
          if (val.id === row.id) {
            val.scrapCount = Number(row.scrapCount)
            if (Number(val.quantityInStock) < Number(row.scrapCount)) {
              this.$Message.warning(({
                content: '当前报废数量不得大于库存数量!',
                duration: 6,
                closable: true
              }));
              val.scrapCount = ''
            }
          }
        })
      }, 600);
    },
    remarkNumchange(row) {
      this.tablelist.forEach(val => {
        if (val.id === row.id) {
          val.scrapReason = row.scrapReason
          val.useDept = row.useDept
          val.deptCostCenter = row.deptCostCenter
        }
      })
    },
    handleSumit(str) {
      if (!(this.tablelist && this.tablelist.length)) {
        this.$Message.warning('请填写报废信息!')
        return;
      }

      let fileList = []
      fileList = JSON.parse(JSON.stringify(this.uploadList))
      if (str === 'submit') {
        this.paramsInfo.active = 0
      }

      if (this.$route.query.status === 'edit') {
        fileList = this.uploadList.filter(val => val.createBy == localStorage.getItem('ziyunFactoryUserId'))
      }
      this.paramsInfo.backupScrapApplyVos = this.tablelist.map(item => (
        {
          id: item.id,//备件台账主键id
          createBy: localStorage.getItem('ziyunFactoryUserId'),
          createByStr: localStorage.getItem('ziyunFactoryPortalName'),
          backupPurchaseId: item.backupPurchaseId,//采购单id
          purchasePrice: item.purchasePrice,
          materielNo: item.materielNo, //料号
          backupNo: item.backupNo,//备件编号
          locationConfigId: item.locationId,//库位id
          backupConfigId: item.backupId,//仓库id
          shelfConfigId: item.shelfId,
          assets: item.assets,//资产残值
          manageType: item.manageType,//管理类型
          assetId: item.assetId,//资产分类主键id
          assetsOriginal: item.assetsOriginal,//资产原值
          scrapCount: item.scrapCount,//报废数量
          useTime: item.useTime,//使用时间
          useDept: item.useDept,//使用部门
          deptCostCenter: item.deptCostCenter,//部门成本中心
          scrapReason: item.scrapReason,//报废原因
        }
      ))
      const flag = this.tablelist.some(val => !val.locationId)
      if (flag) {
        this.$Message.warning(({content: "请选择报废库位!", duration: 6, closable: true}))
        return
      }
      const scrapCountFlag = this.tablelist.some(val => !val.scrapCount)
      if (scrapCountFlag) {
        this.$Message.warning(({content: "请填写报废数量!", duration: 6, closable: true}))
        return
      }
      this.paramsInfo.attachmentVOS = fileList.map(item => (
        {
          createBy: localStorage.getItem('ziyunFactoryUserId'),
          updateBy: localStorage.getItem('ziyunFactoryUserId'),
          fileName: item.fileName,
          filePath: item.filePath,
          fileUrl: item.fileUrl,
          suffix: item.suffix
        }
      ))
      const data = {
        ...this.paramsInfo
      }
      let url = '/dms/backup/scrapApply/add'
      if (this.$route.query.status === 'edit') {
        this.paramsInfo.attachmentVOS = []
        data.id = this.$route.query.id
        data.approvalId = this.$route.query.approvalId
        data.companyId = undefined
        data.backupConfigId = undefined
        url = '/dms/backup/scrapApply/update'
      }
      this.axios({
        method: 'post',
        url,
        data
      }).then(res => {
        if (res.code == 200) {
          this.close()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    async addTableinfo(obj) {
      if (!obj.assetId) {
        obj.assetId = 2
      }
      if (obj.assetId !== 2) {
        obj.scrapCount = 1
      }
      // this.idNum++;
      // const obj  = JSON.parse(JSON.stringify(this.searchParams))
      // if (obj.companyName){
      //   obj.companyId = this.companyList.find(val=>val.id === obj.companyName).id
      //   obj.companyName = this.companyList.find(val=>val.id === obj.companyName).name
      // }
      // if (obj.backupId){
      //   obj.backupName = this.warehouseList.find(val=>val.id === obj.backupId).backupName
      // }
      this.paramsInfo = {
        companyId: obj.companyId,
        backupConfigId: obj.backupConfigId,
        active: -1,
        scrapSource: 0,
        backupScrapApplyVos: [],
        attachmentVOS: []
      }
      const tableObj = {
        // objId:this.idNum,
        id: obj.id,
        backupPurchaseId: obj.backupPurchaseId,
        purchasePrice: obj.purchasePrice,
        materielNo: obj.materielNo, //料号
        backupNo: obj.backupNo,//备件编号
        locationId: obj.locationConfigId,//库位id
        assets: obj.assets,//资产残值
        manageType: obj.manageType,//管理类型
        assetId: obj.assetId,//资产分类主键id
        assetsOriginal: obj.assetsOriginal,//资产原值
        scrapCount: obj.scrapCount,//报废数量
        useTime: obj.useTime,//使用时间
        useDept: obj.useDept,//使用部门
        deptCostCenter: obj.deptCostCenter,//部门成本中心
        scrapReason: obj.scrapReason,//报废原因
        goodsName: obj.goodsName,
        specification: obj.specification,
        companyName: obj.companyName,
        companyId: obj.companyId,
        backupId: obj.backupConfigId,
        shelfId: obj.shelfConfigId,
        quantityInStock: obj.quantityInStock
      }
      this.searchParams = {}
      await this.getCompanyList(tableObj)
      await this.getBackupsByCompany(1, tableObj)
      await this.getShelfByBackupId(1, tableObj);
      await this.baogetLocationByShelfId(1, tableObj, {scrapStatus: 1});
      this.tablelist.push(tableObj)
    },
    addInfolist() {
      this.axios({
        method: 'get',
        url: '/dms/backup/scrapApply/checkBackupCanBeScrap',
        params: {
          scrapSource: 0,
          backupId: this.backupNoObj.id
        }
      }).then(res => {
        if (res.code === 200) {
          this.addTableinfo(res.data)
          this.depreciationInfo = res.data.depreciation
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    getApplicationOAList(query) {
      if (query !== '') {
        this.loading = true
        this.axios({
          method: 'get',
          url: '/basic/user/searchOAUser',
          params: {
            key: query
          }
        }).then(res => {
          if (res.code === 200) {
            this.OAList = res.data.map(item => {
              return {
                ...item,
                showName: item.empno + '----' + item.username
              }
            })
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.OAList = []
      }
    },
    handleMaterielNo(val) {
      if (val) {
        this.materielNoObj = this.materielNoList.find(item => item.id === val)
        if (this.materielNoObj.assetId) {
          this.searchParams.assetTypeName = this.materielNoObj.assetId
        } else {
          this.searchParams.assetTypeName = 2
        }
      } else {
        this.materielNoObj = {}
      }
      this.remoteMethodBack()
    },
    async handleBackupNo(val) {
      if (val) {
        this.backupNoObj = this.backupNoList.find(item => item.id === val)
      } else {
        // this.companyClear()
        this.backupNoObj = {}
      }
      if (JSON.stringify(this.backupNoObj) !== '{}') {
        this.backupNoObj.backStatus = true
        this.backupNoObj.backupId = this.backupNoObj.backupConfigId
        this.backupNoObj.shelfId = this.backupNoObj.shelfConfigId
        // this.searchParams.assetTypeName = this.backupNoObj.assetType
        this.searchParams.companyName = this.backupNoObj.companyId
        this.searchParams.backupId = this.backupNoObj.backupConfigId
        this.searchParams.shelfId = this.backupNoObj.shelfConfigId
        this.searchParams.locationId = this.backupNoObj.locationConfigId
        // await this.getCompanyList(this.backupNoObj)
        await this.getBackupsByCompany(1, this.backupNoObj)
        await this.getShelfByBackupId(1, this.backupNoObj);
        await this.baogetLocationByShelfId(1, this.backupNoObj, {scrapStatus: 0});
      }
    },
    remoteMethod(value) {
      // if (this.materielNoList && this.materielNoList.length){
      //   return
      // }
      this.axios({
        method: 'get',
        url: '/dms/backup/scrapApply/getMaterielInfo',
        params: {
          param: value
        }
      }).then(res => {
        if (res.code === 200) {
          this.materielNoList = res.data
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    clearList() {
      if (!this.searchParams.materielNo && !this.searchParams.backupNo) {
        this.backupNoList = []
        this.materielNoList = []
      }
    },
    remoteMethodBack(value) {
      // this.backupNoList = []
      // if (this.backupNoList && this.backupNoList.length){
      //   return
      // }
      const data = {
        backupNo: value,
        materielNo: this.materielNoObj.materielNo,
        companyId: this.searchParams.companyName,
        backupConfigId: this.searchParams.backupId,
        shelfConfigId: this.searchParams.shelfId,
        locationConfigId: this.searchParams.locationId,
        assetTypeInteger: this.searchParams.assetTypeName
      }
      if (this.searchParams.assetTypeName !== 2 && this.searchParams.assetTypeName) {
        data.assetTypeInteger = 1
      }
      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/getBackupInfo',
        data
      }).then(res => {
        if (res.code === 200) {
          this.backupNoList = []
          this.backupNoList = res.data
          if (this.tablelist && this.tablelist.length) {
            this.tablelist.forEach(val => {
              this.backupNoList = this.backupNoList.filter(list => list.backupNo !== val.backupNo)
            })
          }
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    delRow(row) {
      this.tablelist = this.tablelist.filter(val => val.id !== row.id)
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      }
      this.axios({
        method: 'get',
        url: '/dms/applyUse/querySearch',
        params: params
      }).then(res => {
        if (res.code === 200) {
          // this.dataArr = res.data.list
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    close() {
      this.$router.go(-1)
    },
    clearBackup() {
      this.backupNoObj = {}
      this.backupNoList = []
      this.searchParams.backupNo = ''
    },
    companySelectChange(value, row) {
      this.clearBackup()
      this.getBackupsByCompany(value, row);
    },
    warehouseSelectChange(value, row) {
      this.clearBackup()
      this.getShelfByBackupId(value, row);
    },
    shelvesSelectChange(value, row) {
      this.clearBackup()
      const obj = {
        scrapStatus: 0
      }
      if (row) {
        obj.scrapStatus = 1
      }
      this.baogetLocationByShelfId(value, row, obj);
    },
    companyClear() {
      this.searchParams.companyName = ''
      this.$refs.warehouseSelect.clearSingleSelect();
      this.warehouseList = []
      this.shelvesList = []
      this.locationList = []
    },
    warehouseClear() {
      this.$refs.shelvesSelect.clearSingleSelect();
      this.shelvesList = []
      this.locationList = []
    },
    shelvesClear() {
      this.$refs.locationSelect.clearSingleSelect();
      this.locationList = []
    },
    //公司列表
    getCompanyList(row) {
      return getCompanyList().then(res => {
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id
            }
          })
          if (row && !row.backStatus) {
            row.companyrowList = [...arr]
            this.tablelist.forEach(val => {
              if (val.objId === row.id) {
                // row.companyrowList = [...arr]
                // val.companyrowList = [...arr]
                this.$set(val, 'warehouserowList', arr)
              }
            })
          } else {
            this.companyList = [...this.companyList, ...arr]
          }
          this.$forceUpdate()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    getBackupsByCompany(companyId, row) {
      if (!companyId) {
        return;
      }
      let params = {
        companyId: companyId
      }
      if (row) {
        params.companyId = row.companyId
      }
      return getBackupsByCompany(params).then(res => {
        if (res.code === 200) {
          if (row && !row.backStatus) {
            row.warehouserowList = res.data;
            this.tablelist.forEach(val => {
              if (val.objId === row.id) {
                this.$set(val, 'warehouserowList', res.data)
              }
            })
          } else {
            this.warehouseList = res.data;
          }
          this.$forceUpdate()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    getShelfByBackupId(delIds, row) {
      if (!delIds) {
        return;
      }
      let params = {
        delIds: [delIds]
      }
      if (this.materielNoObj.materielNo) {
        params.materielNo = this.materielNoObj.materielNo
      }
      if (row) {
        params.delIds = [row.backupId]
      }
      return getShelfByBackupId(params).then(res => {
        if (res.code === 200) {
          if (row && !row.backStatus) {
            row.shelvesrowList = res.data;
            this.tablelist.forEach(val => {
              if (val.objId === row.id) {
                this.$set(val, 'shelvesrowList', [...res.data])
              }
            })
          } else {
            this.shelvesList = res.data;
          }
          this.$forceUpdate()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    baogetLocationByShelfId(delIds, row, obj) {
      if (!delIds) {
        return;
      }
      let params = {
        shelfId: delIds,
        scrapStatus: obj.scrapStatus
      }
      if (row) {
        if (!row.backStatus) {
          this.tablelist.forEach(val => {
            if (val.objId === row.id) {
              val.shelfId = row.shelfId
            }
          })
        }
        params.shelfId = row.shelfId
      }
      return baogetLocationByShelfId(params).then(res => {
        if (res.code === 200) {
          if (!(res.data && res.data.length)) {
            row.locationId = ''
          }
          if (row && !row.backStatus) {
            row.locationrowList = res.data;
            this.tablelist.forEach(val => {
              if (val.objId === row.id) {
                this.$set(val, 'locationrowList', res.data)
              }
            })
            const flag = res.data.some(item => item.id !== row.locationId)
            if (flag) {
              row.locationId = ''
            }
          } else {
            this.locationList = res.data;
          }
          this.$forceUpdate()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.picking {
  height: 100%;
  position: relative;

  .btnList {
    position: absolute;
    bottom: 20px;
    left: 40%;

    .ivu-btn {
      margin: 0 5px;
    }
  }
}

.ivu-card-body {
  padding: 0;
}

.basic-info {
  //padding: 5px 16px;
  border-bottom: 1px solid #e8eaec;

  .basic-info-body {
    margin: 10px;
  }

  .basic-info-title_bot {
    margin-top: 16px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .basic-info-title {
    h2 {
      display: inline-block;
      font-size: 16px;
      padding-left: 10px;
      position: relative;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 7px;
        height: 24px;
        background: #187bdb;
      }
    }
  }

  .search-form {
    padding: 0;

    .ivu-form-item {
      margin: 0;
    }
  }
}
</style>
